package com.internetCafes.spms.web.extend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.base.BaseWebController;
import com.internetCafes.spms.common.module.excel.ExcelUtils;
import com.internetCafes.spms.common.module.excel.po.EntCertiHonorExcel;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.utils.DateUtils;
import com.internetCafes.spms.core.utils.R;
import com.internetCafes.spms.web.extend.model.EntCertiHonor;
import com.internetCafes.spms.web.extend.service.IEntCertiHonorService;
import com.internetCafes.spms.web.extend.vo.EntCertiHonorVo;
import com.internetCafes.spms.web.sys.model.ResourceInfo;
import com.internetCafes.spms.web.sys.service.ResourceInfoService;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import com.sms.common.util.hutool.core.date.DateTime;
import com.sms.common.util.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LinYe
 * @since 2020-12-08
 */
@RestController
@RequestMapping("/cert/entHonor")
public class EntCertiHonorController extends BaseWebController {

    @Autowired
    IEntCertiHonorService iEntCertiHonorService;

    @Autowired
    ResourceInfoService resourceInfoService;

    @SysLog("保存荣誉证书")
    @PostMapping("/save")
    @RequiresPermissions("certificate:certificateInfo:save")
    public R save(@RequestBody EntCertiHonorVo entCertiHonorVo) {
        entCertiHonorVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiHonor> entCertiHonorWrapper = new QueryWrapper<EntCertiHonor>();
        entCertiHonorWrapper.eq("code",entCertiHonorVo.getCode());
        int count = iEntCertiHonorService.count(entCertiHonorWrapper);
        if (count > 0) {
            return R.error("证书已存在");
        }
        iEntCertiHonorService.save(entCertiHonorVo);
        if (StringUtils.isNotBlank(entCertiHonorVo.getCertiPic())) {
            ResourceInfo r = new ResourceInfo(ShiroUtils.getUserEntity().getId(), CommonConstants.RESOURCE_PIC_ENT_HONOR, entCertiHonorVo.getId(), "pic" + File.separator + entCertiHonorVo.getCertiPic());
            resourceInfoService.save(r);
        }
        return R.ok();
    }

    @SysLog("作废荣誉证书")
    @PostMapping("/delete/{id}")
    @RequiresPermissions("certificate:certificateInfo:delete")
    public R delete(@PathVariable("id") Long id) {
        EntCertiHonor entCertiHonor = new EntCertiHonor();
        entCertiHonor.setId(id);
        entCertiHonor.setStatus(CommonConstants.CommonStatus.DELETED);
        if (iEntCertiHonorService.updateById(entCertiHonor)) {
            return R.ok();
        } else {
            return R.error("您要删除的证书不存在");
        }
    }

    @SysLog("更新荣誉证书")
    @PostMapping("/update")
    @RequiresPermissions("certificate:certificateInfo:update")
    public R update(@RequestBody EntCertiHonorVo entCertiHonorVo) {
        if (iEntCertiHonorService.updateById(entCertiHonorVo)) {
            Map<String,Object>params = new HashMap<>();
            if (entCertiHonorVo.getCertiPic()!=null) {
                params.put("moduleCode", CommonConstants.RESOURCE_PIC_ENT_HONOR);
                params.put("moduleId", entCertiHonorVo.getId());
                resourceInfoService.deleteByModuleAndUserId(params);
                if (entCertiHonorVo.getCertiPic()!="") {
                    ResourceInfo r = new ResourceInfo(ShiroUtils.getUserEntity().getId(), CommonConstants.RESOURCE_PIC_ENT_HONOR, entCertiHonorVo.getId(), "pic" + File.separator + entCertiHonorVo.getCertiPic());
                    resourceInfoService.save(r);
                }
            }
            return R.ok();
        } else {
            return R.error("您要更新的证书不存在");
        }
    }

    @GetMapping("/getDetail/{id}")
    @RequiresPermissions("certificate:certificateInfo:info")
    public R get(@PathVariable("id") Long id) {
        EntCertiHonor entCertiHonor =  iEntCertiHonorService.getById(id);
        if (entCertiHonor != null) {
            Map<String,Object>params = new HashMap<>();
            params.put("moduleCode", CommonConstants.RESOURCE_PIC_ENT_HONOR);
            params.put("moduleId", id);
            List<ResourceInfo> resourceInfoList = resourceInfoService.query(params);
            EntCertiHonorVo entCertiHonorVo=new EntCertiHonorVo();
            BeanUtils.copyProperties(entCertiHonor,entCertiHonorVo);
            if (CollectionUtil.isNotEmpty(resourceInfoList)) {
                entCertiHonorVo.setCertiPic(resourceInfoList.get(0).getPath());
            }
            return R.ok().put("data", entCertiHonorVo);
        } else {
            return R.error("您要查询的证书不存在");
        }
    }

    @PostMapping("/paging")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R paging(@RequestBody EntCertiHonorVo entCertiHonorVo) {
        if (entCertiHonorVo.getStatus()==null) {
            entCertiHonorVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        }
        Page<EntCertiHonor> page=new Page<>(entCertiHonorVo.getPageNum(),entCertiHonorVo.getPageSize());
        QueryWrapper<EntCertiHonor> entCertiHonorWrapper = new QueryWrapper<EntCertiHonor>(entCertiHonorVo);
        if (entCertiHonorVo.getName()!=null){
            entCertiHonorWrapper.like("name",entCertiHonorVo.getName());
        }
        if (entCertiHonorVo.getOrderBy()!=null) {
            entCertiHonorWrapper.orderBy(entCertiHonorVo.getOrderBy() != null, entCertiHonorVo.isAscFlag(), com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(entCertiHonorVo.getOrderBy()));
        }
        if (entCertiHonorVo.getWechatParam()!=null){
            entCertiHonorWrapper.and(wrapper -> wrapper.like("name",entCertiHonorVo.getWechatParam()).or().like("code",entCertiHonorVo.getWechatParam()).or().like("release_organ",entCertiHonorVo.getWechatParam()));
        }
        entCertiHonorWrapper.orderBy(true,false,"id");
        if (entCertiHonorVo.getValidityType()!=null) {
            switch (entCertiHonorVo.getValidityType()) {
                case -1:
                    entCertiHonorWrapper.lt("expire_date", new Date());
                    break;
                case 0:
                    entCertiHonorWrapper.gt("expire_date", new Date());
                    entCertiHonorWrapper.lt("expire_date", entCertiHonorVo.getDays() != null && entCertiHonorVo.getDays() != "" ? DateUtils.getBeAfDay(Integer.parseInt(entCertiHonorVo.getDays())) : entCertiHonorVo.getMonths() != null && entCertiHonorVo.getDays() != "" ? DateUtils.getBeAfMonth(Integer.parseInt(entCertiHonorVo.getMonths())) : null);
                    break;
                case 2:
                    entCertiHonorWrapper.lt("expire_date", new Date());
                    entCertiHonorWrapper.or(wrapper -> wrapper.gt("expire_date", new Date()).lt("expire_date", entCertiHonorVo.getDays() != null ? DateUtils.getBeAfDay(Integer.parseInt(entCertiHonorVo.getDays())) : entCertiHonorVo.getMonths() != null ? DateUtils.getBeAfMonth(Integer.parseInt(entCertiHonorVo.getMonths())) : null));
            }
        }
        IPage<EntCertiHonor> entCertiHonorIPage = iEntCertiHonorService.page(page,entCertiHonorWrapper);
        List<EntCertiHonor> records = entCertiHonorIPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            EntCertiHonor entCertiHonor = records.get(i);
            Map<String,Object>params = new HashMap<>();
            params.put("moduleCode", CommonConstants.RESOURCE_PIC_ENT_HONOR);
            params.put("moduleId", entCertiHonor.getId());
            List<ResourceInfo> resourceInfoList = resourceInfoService.query(params);
            if (CollectionUtil.isNotEmpty(resourceInfoList)) {
                EntCertiHonorVo certiHonorVo = new EntCertiHonorVo();
                BeanUtils.copyProperties(entCertiHonor, certiHonorVo);
                certiHonorVo.setCertiPic(resourceInfoList.get(0).getPath());
                records.set(i, certiHonorVo);
            }
        }
        return R.ok().put("data", entCertiHonorIPage);
    }

    @PostMapping("/list")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R list(@RequestBody EntCertiHonorVo entCertiHonorVo) {
        entCertiHonorVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiHonor> entCertiHonorWrapper = new QueryWrapper<EntCertiHonor>(entCertiHonorVo);
        entCertiHonorWrapper.orderBy(entCertiHonorVo.getOrderBy()!=null,entCertiHonorVo.isAscFlag(),entCertiHonorVo.getOrderBy());
        List<EntCertiHonor> list = iEntCertiHonorService.list(entCertiHonorWrapper);
        return R.ok().put("data", list);
    }

    @PostMapping("/export")
    @RequiresPermissions("certificate:certificateInfo:list")
    public void export(@RequestBody EntCertiHonorVo entCertiHonorVo,HttpServletResponse response) {
        entCertiHonorVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiHonor> entCertiHonorWrapper = new QueryWrapper<EntCertiHonor>(entCertiHonorVo);
        entCertiHonorWrapper.orderBy(entCertiHonorVo.getOrderBy()!=null,entCertiHonorVo.isAscFlag(),entCertiHonorVo.getOrderBy());
        List<EntCertiHonor> list = iEntCertiHonorService.list(entCertiHonorWrapper);
        try {
            if (list != null && list.size() > 0) {
                List<EntCertiHonorExcel> orderInfoExcelList = new ArrayList<>();
                EntCertiHonorExcel entCertiHonorExcel;
                for (EntCertiHonor entCertiHonor : list) {
                    entCertiHonorExcel = new EntCertiHonorExcel();
                    BeanUtils.copyProperties(entCertiHonor, entCertiHonorExcel);
                    orderInfoExcelList.add(entCertiHonorExcel);
                }
                ExcelUtils.exportExcel(orderInfoExcelList, "荣誉证书信息统计", "荣誉证书信息统计", EntCertiHonorExcel.class, "荣誉证书信息统计.xls", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/count")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R count(@ModelAttribute EntCertiHonor entCertiHonor) {
        entCertiHonor.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiHonor> entCertiHonorWrapper = new QueryWrapper<EntCertiHonor>(entCertiHonor);
        int count = iEntCertiHonorService.count(entCertiHonorWrapper);
        return R.ok().put("count", count);
    }

    @GetMapping("/levelCount")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R countlevel() {
        QueryWrapper<EntCertiHonor> entCertiHonorQueryWrapper = new QueryWrapper<>();
        entCertiHonorQueryWrapper.eq("level",CommonConstants.HonorLevels.NATIONAL);
        int nationalLevel = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        entCertiHonorQueryWrapper = new QueryWrapper<>();
        entCertiHonorQueryWrapper.eq("level",CommonConstants.HonorLevels.PROVINCIAL);
        int provincialLevel = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        entCertiHonorQueryWrapper = new QueryWrapper<>();
        entCertiHonorQueryWrapper.eq("level",CommonConstants.HonorLevels.MUNICIPAL);
        int municipalLevel = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        entCertiHonorQueryWrapper = new QueryWrapper<>();
        entCertiHonorQueryWrapper.eq("level",CommonConstants.HonorLevels.OTHER);
        int otherLevel = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        return R.ok().put("nationalLevel",nationalLevel)
                .put("provincialLevel",provincialLevel)
                .put("municipalLevel",municipalLevel)
                .put("otherLevel",otherLevel);
    }

    @GetMapping("/yearCount")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R countByYear() {
        Calendar c = Calendar.getInstance();
        QueryWrapper<EntCertiHonor> entCertiHonorQueryWrapper = new QueryWrapper<>();
        entCertiHonorQueryWrapper.ge("release_date",DateUtil.beginOfYear(c.getTime()));
        entCertiHonorQueryWrapper.le("release_date",DateUtil.endOfYear(c.getTime()));
        int thisYearCount = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        entCertiHonorQueryWrapper = new QueryWrapper<>();
        c.add(Calendar.YEAR,-1);
        entCertiHonorQueryWrapper.ge("release_date",DateUtil.beginOfYear(c.getTime()));
        entCertiHonorQueryWrapper.le("release_date",DateUtil.endOfYear(c.getTime()));
        int lastYearCount = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        entCertiHonorQueryWrapper = new QueryWrapper<>();
        c.add(Calendar.YEAR,-1);
        entCertiHonorQueryWrapper.ge("release_date",DateUtil.beginOfYear(c.getTime()));
        entCertiHonorQueryWrapper.le("release_date",DateUtil.endOfYear(c.getTime()));
        int lastTwoYearCount = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        entCertiHonorQueryWrapper = new QueryWrapper<>();
        c.add(Calendar.YEAR,-1);
        entCertiHonorQueryWrapper.ge("release_date",DateUtil.beginOfYear(c.getTime()));
        entCertiHonorQueryWrapper.le("release_date",DateUtil.endOfYear(c.getTime()));
        int lastThreeYearCount = iEntCertiHonorService.count(entCertiHonorQueryWrapper);
        return R.ok().put("thisYearCount",thisYearCount)
                .put("lastYearCount",lastYearCount)
                .put("lastTwoYearCount",lastTwoYearCount)
                .put("lastThreeYearCount",lastThreeYearCount);
    }

    @GetMapping("/yearlist/{year}")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R listByYear(@PathVariable Integer year) {
        Date date = new Date(year-1900, 1, 1);
        QueryWrapper<EntCertiHonor> entCertiHonorQueryWrapper = new QueryWrapper<>();
        entCertiHonorQueryWrapper.ge("release_date",DateUtil.beginOfYear(date));
        entCertiHonorQueryWrapper.le("release_date",DateUtil.endOfYear(date));
        entCertiHonorQueryWrapper.orderBy(true,true,"level");
        List<EntCertiHonor> list = iEntCertiHonorService.list(entCertiHonorQueryWrapper);
        return R.ok().put("data",list);
    }

}
